package org.aceor.mddal.common.sqlparser.result.object;

import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * Created by lxue on 16/3/24.
 */
public class Column {
    private Table table = new Table();//TODO: 这里直接new感觉有风险
    private String name;
    private String alias;

    public static final Column allColumn = new Column("*");

    public Column() {
    }

    public Column(Table table, String name) {
        this.table = table;
        Preconditions.checkNotNull(name);
        this.name = name;
    }

    public Column(String name) {
        this.name = name;
        Preconditions.checkNotNull(name);
    }

    public Column(String name, String alias) {
        this.name = name;
        this.alias = alias;
    }

    public Table getTable() {
        return table;
    }

    public void setTable(Table table) {
        this.table = table;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(table, name, alias);
    }

    @Override
    public boolean equals(Object obj) {
        if (null == obj) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Column)) {
            return false;
        }
        Column other = (Column) obj;
        return Objects.equal(other.alias, alias) && Objects.equal(other.name, name) && Objects.equal(other.table, table);
    }

    @Override
    public String toString() {
        return toStringHelper(false);
    }

    public String toStringIgnoreAlias() {
        return toStringHelper(true);
    }

    private String toStringHelper(boolean ignoreAlias) {
        if (null == table
                || (table.getName() == null && table.getAlias() == null)) {
            return getColumnName(ignoreAlias);
        } else {
            return Joiner.on("").join(table, ".", getColumnName(ignoreAlias));
        }
    }

    private String getColumnName(boolean ignoreAlias) {
        if (ignoreAlias || Strings.isNullOrEmpty(alias)) {
            return name;
        } else {
            return Joiner.on("").join(name, " ", alias);
        }
    }
}
